package net.lcheng.shop.Controller;

import com.alibaba.fastjson.JSONObject;
import net.lcheng.model.*;
import net.lcheng.service.ShoppingService;
import net.lcheng.service.TradeManageService;
import net.lcheng.service.UserService;
import net.lcheng.service.WxShopService;
import net.lcheng.shop.vo.CurrentUserModel;
import net.lcheng.shop.vo.RefundAddressModel;
import net.lcheng.shop.vo.SellerSendGoodsModel;
import net.lcheng.utils.Oorder2OrderModel;
import net.lcheng.utils.OorderRefund2OrderRefundModel;
import net.lcheng.vo.OrderModel;
import net.lcheng.vo.OrderRefundModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by LV on 2016/7/21.
 */
@Controller
public class SellerOrderManageController {

    @Autowired
    private UserService userService;
    @Autowired
    private WxShopService shopService;
    @Autowired
    private TradeManageService tradeManageService;
    @Autowired
    private ShoppingService shoppingService;

    /**
     * 获取买家所有订单
     * @param model 模型
     * @return String
     */
    @RequestMapping(value = "/sellerOrder/getAllOrders",method = RequestMethod.GET)
    public String getAllOrders(Model model){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user != null) {
                    //获取该用户的店铺（一个用户对应一个店铺）
                    WxShop shop = shopService.getShopInforByUserId(user.getUserId());
                    if (shop != null) {
                        List<OOrder> list=tradeManageService.getAllOrdersByShopId(shop.getShopId());
                        //转换对象，解析订单订单商品的json串
                        List<OrderModel> orderModelList=Oorder2OrderModel.getOorder2OrderModel(list);
                        model.addAttribute("orderModelList",orderModelList);
                        return "/seller_orders/all_orders";
                    }
                    return "redirect:/error";
                }
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     *根据订单状态，获取买家该状态下的所有订单
     * @param model 模型
     * @param orderStatus 订单状态
     * @return String
     */
    @RequestMapping(value = "/sellerOrder/getAllOrderByStatus",method = RequestMethod.GET)
    public String getAllOrderByStatus(Model model,@RequestParam("status") int orderStatus){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user != null) {
                    //获取该用户的店铺（一个用户对应一个店铺）
                    WxShop shop = shopService.getShopInforByUserId(user.getUserId());
                    if (shop != null) {
                        List<OOrder> list=tradeManageService.getAllOrdersByShopIdAndOrderStatus(shop.getShopId(),orderStatus);
                        //转换对象，解析订单订单商品的json串
                        List<OrderModel> orderModelList=Oorder2OrderModel.getOorder2OrderModel(list);
                        model.addAttribute("orderModelList",orderModelList);
                        model.addAttribute("orderStatus",orderStatus);

                        return "/seller_orders/order_status";
                    }
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 卖家取消订单
     * @param orderId 要取消的订单Id
     * @return String
     */
    @RequestMapping(value = "/sellerOrder/cancelOrder",method = RequestMethod.GET)
    public String cancelOrder(@RequestParam("oid") String orderId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (orderId!=null&&!orderId.equals("")){
                //查找订单信息
                OOrder order=tradeManageService.getOrderByPrimaryKey(orderId);
                order.setOrderStatus(-1);//订单的状态为取消状态
                order.setOrderCancelDescription("卖家主动取消");
                order.setModifyOn(new Date());
                int status=tradeManageService.cancelOrderBySeller(order);
                if (status>0)
                    return "redirect:/sellerOrder/getAllOrders";
                else
                    return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }
    /**
     * 卖家发货
     * @param model 模型
     * @param orderId 订单主键
     * @return String
     */
    @RequestMapping(value = "/sellerOrder/sendGoodsBySeller",method = RequestMethod.GET)
    public String sendGoodsBySeller(Model model,@RequestParam("oid") String orderId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (orderId!=null){
                //获取该订单信息
                OOrder order=tradeManageService.getOrderByPrimaryKey(orderId);
                //转换对象，解析商品列表的Json数据
                OrderModel orderModel=Oorder2OrderModel.getOorder2OrderModel(order);
                model.addAttribute("orderModel",orderModel);
                return "/seller_orders/order_send_goods";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存商家发货信息
     * @param model 模型
     * @param goodsModel 接收模型
     * @param result 验证结果对象
     * @return String
     */
    @RequestMapping(value = "/sellerOrder/savingShippingInformation",method = RequestMethod.POST)
    public String savingShippingInformation(Model model, @Valid @ModelAttribute("goodsModel") SellerSendGoodsModel goodsModel, BindingResult result){
        if (result.hasErrors()){
            if (goodsModel.getOrderId()!=null){
                //获取该订单信息
                OOrder order=tradeManageService.getOrderByPrimaryKey(goodsModel.getOrderId());
                //转换对象，解析商品列表的Json数据
                OrderModel orderModel=Oorder2OrderModel.getOorder2OrderModel(order);
                model.addAttribute("orderModel",orderModel);
                model.addAttribute("goodsModel",goodsModel);
                return "/seller_orders/order_send_goods";
            }else
                return "redirect:/error";
        }

        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (goodsModel != null && goodsModel.getOrderId() != null){

                OOrder order = new OOrder();
                    order.setOrderId(goodsModel.getOrderId());//主键
                    order.setShippingCompanyName(goodsModel.getShippingName());
                    order.setShippingCompanyCode(goodsModel.getShippingCode());
                    order.setShippingTrackingNumber(goodsModel.getShippingNum());//快递号
                    order.setShippingTime(new Date());
                    order.setOrderStatus(2);//订单状态改变为订单已发货
                //更新订单信息
                int status=tradeManageService.updateOOrderByPrimaryKey(order);
                //发货完成，添加订单日志信息
                if (status>0){
                    OOrder oOrder=tradeManageService.getOrderByPrimaryKey(goodsModel.getOrderId());
                    if (oOrder!=null) {
                        //添加订单日志信息
                        OOrderHistory history = new OOrderHistory();
                        history.setHistoryId(UUID.randomUUID().toString());
                        history.setComment("卖家已发货");
                        history.setoOrderOrderId(goodsModel.getOrderId());
                        history.setOrderStatus(2);
                        history.setCreateOn(new Date());
                        history.setCreateBy(oOrder.getSellerShopName());
                        int hStatus=tradeManageService.addOrderHistory(history);
                        if (hStatus>0)
                            return "redirect:/sellerOrder/getAllOrderByStatus?status=1";
                        else
                            return "redirect:error";
                    }
                    return "redirect:error";
                }
                return "redirect:error";
            }
            return "redirect:error";
        }
        return "redirect:/login";
    }


    /**
     * 取消退货订单及发货（处理未发货的退款订单）
     * @param orderRefundId 要处理的退货订单
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/cancelRefundThenSendGoods",method = RequestMethod.GET)
    public String cancelRefundThenSendGoods(Model model,@RequestParam("orId") String orderRefundId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //获取退货订单信息
            if (orderRefundId!=null&&!orderRefundId.equals("")) {
                OOrderRefund orderRefund = tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
                if (orderRefund != null) {
                    //获取该订单信息
                    OOrder order = tradeManageService.getOrderByPrimaryKey(orderRefund.getOrderId());
                    //转换对象，解析商品列表的Json数据
                    OrderModel orderModel = Oorder2OrderModel.getOorder2OrderModel(order);
                    model.addAttribute("orderModel", orderModel);
                    model.addAttribute("orderRefundId",orderRefundId);
                    return "/seller_refund_orders/refund_order_send_goods";
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存发货信息
     * @param model 模型
     * @param orderRefundId 退货订单Id
     * @param goodsModel 物流信息
     * @param result 验证结果
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/savingCancelRefundThenSendGoods",method = RequestMethod.POST)
    public String savingCancelRefundThenSendGoods(Model model,String orderRefundId,@Valid @ModelAttribute("goodsModel") SellerSendGoodsModel goodsModel, BindingResult result){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (result.hasErrors()){
                if (orderRefundId!=null&&!orderRefundId.equals("")) {
                    OOrderRefund orderRefund = tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
                    if (orderRefund != null) {
                        //获取该订单信息
                        OOrder order = tradeManageService.getOrderByPrimaryKey(orderRefund.getOrderId());
                        //转换对象，解析商品列表的Json数据
                        OrderModel orderModel = Oorder2OrderModel.getOorder2OrderModel(order);
                        model.addAttribute("orderModel", orderModel);
                        model.addAttribute("orderRefundId",orderRefundId);
                        return "/seller_refund_orders/refund_order_send_goods";
                    }
                    return "redirect:/error";
                }
                return "redirect:/error";
            }

            //如果没有验证错误，保存发货信息，取消退货订单
            if (orderRefundId!=null&&!orderRefundId.equals("")&&goodsModel!=null){
                //获取退货订单信息
                OOrderRefund orderRefund = tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
                    if (orderRefund!=null) {
                        int status = shoppingService.deliverGoodsThenCancelRefundOrder(orderRefundId, goodsModel.getShippingCode(),
                                goodsModel.getShippingName(), goodsModel.getShippingNum());
                        if (status > 0)
                            return "redirect:/userRefundOrder/getAllRefundOrderByStatus?sid=" + orderRefund.getWxShopShopId()+"&status=0";//退货订单待审核列表
                        else
                            return "redirect:/error";
                    }

            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 卖家同意退款（卖家未发货）
     * @param model 模型
     * @param orderRefundId 退款订单Id
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/agreeRefundMoney",method =RequestMethod.GET)
    public String agreeRefundMoney(Model model,@RequestParam("orId") String orderRefundId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (orderRefundId!=null&&!orderRefundId.equals("")){
                //获取退货订单信息
                OOrderRefund orderRefund=tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);

                //todo 添加卖家退款买家动作并将退款订单状态更改为完成状态
                /**这里暂时模拟支付完成，退款订单状态变更为已完成,添加订单记录**/
                OOrderRefund orderRefund1=new OOrderRefund();
                orderRefund1.setOrderRefundId(orderRefund.getOrderRefundId());//主键
                orderRefund1.setOrderStatus(3);//已完成退款状态
                //更新数据库
                int status=tradeManageService.updateOOrderRefundByPrimaryKey(orderRefund1);

                //获取原订单信息
                OOrder order=tradeManageService.getOrderByPrimaryKey(orderRefund.getOrderId());
                OOrder order1=new OOrder();
                order1.setOrderId(order.getOrderId());
                order1.setOrderStatus(-1);//退款成功后，原订单为已取消状态
                int status1=tradeManageService.updateOOrderByPrimaryKey(order1);

                if(status>0&&status1>0){
                    //添加订单日志信息
                    OOrderHistory history = new OOrderHistory();
                    history.setHistoryId(UUID.randomUUID().toString());
                    history.setComment("卖家已退款");
                    history.setoOrderOrderId(orderRefund.getOrderId());
                    history.setOrderStatus(-1);//已完成退款状态
                    history.setCreateOn(new Date());
                    history.setCreateBy(orderRefund.getSellerShopName());
                    int hStatus=tradeManageService.addOrderHistory(history);

                    if (hStatus>0){
                        return "redirect:/userRefundOrder/getAllRefundOrderByStatus?sid=" + orderRefund.getWxShopShopId()+"&status=0";//返回退款订单审核列表
                    }
                    else
                        return "redirect:/error";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 卖家同意退款退货
     * @param model 模型
     * @param orderRefundId 退款订单Id
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/agreeRefundMoneyAndGoods",method = RequestMethod.GET)
    public String agreeRefundMoneyAndGoods(Model model,@RequestParam("orId") String orderRefundId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (orderRefundId!=null&&!orderRefundId.equals("")){
                //获取退单信息
                OOrderRefund orderRefund=tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
                model.addAttribute("orderRefund",orderRefund);
                return "/seller_refund_orders/agree_return_good_and_money";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }


    /**
     * 保存退货退款信息
     * @param model 模型
     * @param orderRefundId 退货订单Id
     * @param addressModel vo
     * @param result 验证信息
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/savingAgreeRefundInformation",method = RequestMethod.POST)
    public String savingAgreeRefundInformation(Model model,String orderRefundId,@Valid @ModelAttribute("addressModel") RefundAddressModel addressModel,BindingResult result){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (result.hasErrors()){
                if (orderRefundId!=null&&!orderRefundId.equals("")){
                    //获取退单信息
                    OOrderRefund orderRefund=tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
                    model.addAttribute("orderRefund",orderRefund);
                    return "/seller_refund_orders/agree_return_good_and_money";
                }
                return "redirect:/error";
            }
            //验证通过
            if (orderRefundId!=null&&!orderRefundId.equals("")&&addressModel!=null){

                //获取退单信息
                OOrderRefund orderRefund=tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
                //保存退货信息
                orderRefund.setOrderRefundId(orderRefundId);//主键
                orderRefund.setProvinceCode(addressModel.getProvinceCode());
                orderRefund.setProvinceName(addressModel.getProvinceName());
                orderRefund.setCityCode(addressModel.getCityCode());
                orderRefund.setCityName(addressModel.getCityCode());
                orderRefund.setDistrictCode(addressModel.getDistrictCode());
                orderRefund.setDistrictName(addressModel.getDistrictName());
                orderRefund.setAddress(addressModel.getAddress());
                orderRefund.setPaymentMoneyAmount(new BigDecimal(addressModel.getRefundAccount()));

                int status=shoppingService.agreeRefundMoneyAndGoods(orderRefund);

                if (status>0)
                    return "redirect:/sellerOrder/getAllOrderByStatus?status=0";
                else
                    return "redirect:/error";
            }
            return "redirect:/error";

        }
        return "redirect:/login";
    }



    /**
     * 获取所有退款订单
     * @param model 模型
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/getAllRefundOrders",method = RequestMethod.GET)
    public String getAllRefundOrders(Model model){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user != null) {
                    //获取该用户的店铺（一个用户对应一个店铺）
                    WxShop shop = shopService.getShopInforByUserId(user.getUserId());
                    if (shop != null) {
                        List<OOrderRefund> orderRefundList=tradeManageService.getAllRefundOrdersByShopId(shop.getShopId());
                        //转换对象，解析退货订单包含的子商品json串
                        List<OrderRefundModel> orderRefundModelList= OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(orderRefundList);
                        model.addAttribute("orderRefundModelList",orderRefundModelList);
                        return "/seller_refund_orders/all_refund_orders";
                    }
                    return "redirect:/error";
                }
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 获取对应状态所有退款订单
     * @param model 模型
     * @param orderStatus 订单状态
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/getAllRefundOrdersByStatus",method = RequestMethod.GET)
    public String getAllRefundOrdersByStatus(Model model,@RequestParam("status") int orderStatus){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            Session session = currentUser.getSession();
            //String userId = session.getAttribute("userId").toString();
            CurrentUserModel currentUserModel = JSONObject.parseObject(session.getAttribute("user").toString(), CurrentUserModel.class);
            User user = userService.getUserByUserId(currentUserModel.getUserId());
                if (user != null) {
                    //获取该用户的店铺（一个用户对应一个店铺）
                    WxShop shop = shopService.getShopInforByUserId(user.getUserId());
                    if (shop != null) {
                        List<OOrderRefund> orderRefundList=tradeManageService.getAllRefundOrdersByShopIdAndOrderStatus(shop.getShopId(),orderStatus);
                        //转换对象，解析退货订单包含的子商品json串
                        List<OrderRefundModel> orderRefundModelList= OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(orderRefundList);
                        model.addAttribute("orderRefundModelList",orderRefundModelList);
                        model.addAttribute("orderStatus",orderStatus);
                        return "/seller_refund_orders/refund_order_status";
                    }
                    return "redirect:/error";
                }
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 退货订单处理（卖家已发货）
     * @param model 模型
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/haveSendGoodsInformation",method = RequestMethod.GET)
    public String haveSendGoodsInformation(Model model,@RequestParam("rfId") String refundOrderId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (refundOrderId!=null){
                //退货订单信息
                OOrderRefund orderRefund=tradeManageService.getOorderRefundByPrimaryKey(refundOrderId);
                if (orderRefund!=null) {
                    //获取原订单信息
                    OOrder order = tradeManageService.getOrderByPrimaryKey(orderRefund.getOrderId());
                    OrderModel orderModel = Oorder2OrderModel.getOorder2OrderModel(order);
                    model.addAttribute("orderModel", orderModel);
                    //转换对象
                    OrderRefundModel orderRefundModel = OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(orderRefund);
                    model.addAttribute("orderRefundModel", orderRefundModel);
                    return "/seller_refund_orders/have_send_goods_order_infor";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 退货订单处理（卖家未发货）
     * @param model 模型
     * @param refundId 退货订单Id
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/notSendGoodsInformation",method = RequestMethod.GET)
    public String notSendGoodsInformation(Model model,@RequestParam("rfId") String refundId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            if (refundId!=null){
                //退货订单信息
                OOrderRefund refund=tradeManageService.getOorderRefundByPrimaryKey(refundId);

                if (refund!=null) {
                    //获取原订单信息
                    OOrder order=tradeManageService.getOrderByPrimaryKey(refund.getOrderId());
                    OrderModel orderModel=Oorder2OrderModel.getOorder2OrderModel(order);
                    model.addAttribute("orderModel",orderModel);
                    //转换对象
                    OrderRefundModel refundModel = OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(refund);
                    model.addAttribute("orderRefundModel", refundModel);
                    return "/seller_refund_orders/not_send_goods_order_infor";
                }
                return "redirect:/error";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 卖家确认收货
     * @param orderRefundId 确认收货的退单
     * @return String
     */
    @RequestMapping(value = "/sellerRefundOrder/confirmReceiveGoods",method = RequestMethod.GET)
    public String confirmReceiveGoods(@RequestParam("orId") String orderRefundId){
        Subject currentUser= SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            //卖家确认收货，需要执行退款动作，取消原订单
            /**暂时模拟卖家确认收货**/ //Todo
            //获取退单的信息
            OOrderRefund orderRefund=tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
            orderRefund.setOrderStatus(3);
            orderRefund.setGoodsGetTime(new Date());
            //更新退款订单
            tradeManageService.updateOOrderRefundByPrimaryKey(orderRefund);
            return "redirect:/sellerRefundOrder/getAllRefundOrders";
        }
        return "redirect:/login";
    }
}
